﻿using JWT;
using JWT.Algorithms;
using JWT.Serializers;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using WebApiFrameworkJWTDemo.Model;

namespace WebApiFrameworkJWTDemo.Common
{
    public class JWTUtil
    {
        public static string key = "ASDwsxRTY158mkyIJN369";

        /// <summary>
        /// 把源数据转换成JWT加密串
        /// </summary>
        /// <param name="payload"></param>
        /// <returns></returns>
        public static string Encode(object payload)
        {
            return Encode(payload, key);
        }

        /// <summary>
        /// 把源数据转换成JWT加密串
        /// </summary>
        /// <param name="payload">源数据</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public static string Encode(object payload, string key)
        {
            IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
            IJsonSerializer serializer = new JsonNetSerializer();
            IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
            IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
            string token = encoder.Encode(payload, key);
            return token;
        }

        /// <summary>
        /// 把JWT加密串转换成源数据
        /// </summary>
        /// <param name="token">密文</param>
        /// <returns></returns>
        public static string Decode(string token)
        {
            return Decode(token, key);
        }

        /// <summary>
        /// 把JWT加密串转换成源数据
        /// </summary>
        /// <param name="token">密文</param>
        /// <param name="key">密钥</param>
        /// <returns></returns>
        public static string Decode(string token, string key)
        {
            try
            {
                IJwtAlgorithm algorithm = new HMACSHA256Algorithm();
                IJsonSerializer serializer = new JsonNetSerializer();
                IDateTimeProvider provider = new UtcDateTimeProvider();
                IJwtValidator validator = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
                string json = decoder.Decode(token, key, true);
                return json;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 校验用户是否已登陆
        /// </summary>
        /// <returns></returns>
        public static Tuple<bool, LoginViewModel> ValidateLogin(HttpRequest request)
        {
            try
            {
                if (request.Headers["token"] == null) return new Tuple<bool, LoginViewModel>(false, null);
                LoginViewModel model = JsonConvert.DeserializeObject<LoginViewModel>(Decode(request.Headers["token"], key));
                if (DateTime.Now > model.Expiration.AddMinutes(ConfigUtil.TokenCacheMinutes))
                {
                    return new Tuple<bool, LoginViewModel>(false, null);
                }
                return new Tuple<bool, LoginViewModel>(true, model);
            }
            catch (Exception ex)
            {
                return new Tuple<bool, LoginViewModel>(false, null);
            }
        }
    }
}
